package com.hospital.post.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

public class Tools
{

    public static double val(String str)
    {
        double dem = 1.0;
        int num = 0, sign = 1;
        boolean pointed = false;
        if (str == null || str.isBlank())
        {
            return 0.;
        }
        str=str.trim();
        for (int i = 0; i < str.length(); i++)
        {
            if (i == 0 && str.charAt(0) == '-')
            {
                sign = -1;
                continue;
            } else if (i == 0 && str.charAt(0) == '+')
            {
                continue;
            }
            if (!pointed && str.charAt(i) == '.')
            {
                pointed = true;
                continue;
            }
            if (str.charAt(i) < '0' || str.charAt(i) > '9')
            {
                break;
            }

            num = num * 10 + (str.charAt(i) - '0');
            if (pointed)
            {
                dem *= 10;
            }
        }
        return num * sign / dem;
    }

    public static int intval(String str)
    {
        int num = 0, sign = 1;
        if (str == null || str.isBlank())
        {
            return 0;
        }
        str=str.trim();
        for (int i = 0; i < str.length(); i++)
        {
            if (i == 0 && str.charAt(0) == '-')
            {
                sign = -1;
                continue;
            } else if (i == 0 && str.charAt(0) == '+')
            {
                continue;
            }
            if (str.charAt(i) < '0' || str.charAt(i) > '9')
            {
                break;
            }

            num = num * 10 + (str.charAt(i) - '0');
        }
        return num * sign;
    }


    public static boolean checkMySQLName(String name)
    {
        return name.matches("^[a-z,A-Z]{1}[a-z,A-Z,0-9,_]{0,63}$");
    }

    public static String duoBase64Decode(String str)
    {
        return new String(Base64.getDecoder().decode(Base64.getDecoder().decode(str)));
    }

    public static String duoBase64Encode(String str)
    {
        return Base64.getEncoder().encodeToString(Base64.getEncoder().encodeToString(str.getBytes()).getBytes());
    }

    public static String MD5(String input) throws Exception {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte messageDigest[] = md.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest)
            {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1)
                {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
    }

}
